/*
 *  Copyright 2019-2023 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import me.zhengjie.exception.BizException;
import me.zhengjie.modules.system.domain.AddressDetail;
import me.zhengjie.modules.system.domain.WxUser;
import me.zhengjie.modules.system.domain.req.AddressReq;
import me.zhengjie.modules.system.domain.vo.AddressDetailQueryCriteria;
import me.zhengjie.modules.system.mapper.AddressDetailMapper;
import me.zhengjie.modules.system.service.AddressDetailService;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.WxUserService;
import me.zhengjie.modules.system.domain.vo.WxUserQueryCriteria;
import me.zhengjie.modules.system.mapper.WxUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

import static me.zhengjie.modules.biz.domain.enums.ErrorCode.NOT_SET_CHANNEL;
import static me.zhengjie.modules.biz.domain.enums.ErrorCode.USER_ID_NOT_NULL;

/**
 * @description 服务实现
 * @author yiwei.he
 * @date 2024-03-22
 **/
@Service
@RequiredArgsConstructor
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements WxUserService {

    private final WxUserMapper wxUserMapper;

    private final AddressDetailService addressDetailService;

    private final AddressDetailMapper addressDetailMapper;

    @Override
    public PageResult<WxUser> queryAll(WxUserQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(wxUserMapper.findAll(criteria, page));
    }

    @Override
    public List<WxUser> queryAll(WxUserQueryCriteria criteria){
        return wxUserMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(WxUser resources) {
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(WxUser resources) throws BizException {
        WxUser wxUser = getById(resources.getId());
        if(wxUser == null){
            throw new BizException(USER_ID_NOT_NULL.getCode(),USER_ID_NOT_NULL.getMessage());
        }
        wxUser.copy(resources);
        saveOrUpdate(wxUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<WxUser> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (WxUser wxUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户唯一标识", wxUser.getOpenId());
            map.put("昵称", wxUser.getNickName());
            map.put("性别", wxUser.getGender());
            map.put("城市", wxUser.getCity());
            map.put("省份", wxUser.getProvince());
            map.put("国家", wxUser.getCountry());
            map.put("头像", wxUser.getAvatarUrl());
            map.put("用户在开放平台的唯一标识", wxUser.getAppId());
            map.put("是否授权", wxUser.getIsAuth());
            map.put("创建时间", wxUser.getCreateTime());
            map.put("sessionkey", wxUser.getSessionkey());
            map.put("VIP【0：不是，1：是】", wxUser.getIsVip());
            map.put("推荐次数", wxUser.getRecommendNum());
            map.put("推广二维码", wxUser.getImgCode());
            map.put("手机号", wxUser.getPhone());
            map.put("生日", wxUser.getBirthday());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public WxUser selectById(WxUserQueryCriteria criteria) {
        // 过滤sessionkey和openId
        return  wxUserMapper.selectOne(new QueryWrapper<WxUser>().select(WxUser.class, info -> !info.getColumn().equals("sessionkey") && !info.getColumn().equals("open_id")).eq("id", criteria.getUserId()));
    }

    @Override
    @Transactional
    public Boolean updateAddress(AddressDetailQueryCriteria req) {
        if(req.getIsDefault() != null && req.getIsDefault() == 1){
            // 搜索是否有默认的地址，如果有，将之前默认的地址取消。
            AddressDetail addressDetail = addressDetailMapper.selectOne(new QueryWrapper<AddressDetail>()
                    .eq("user_id", req.getUserId())
                    .eq("is_default", 1));
            if(addressDetail != null){
                addressDetail.setIsDefault(0);
                addressDetailMapper.updateById(addressDetail);
            }
        }
        AddressDetail addressDetail = new AddressDetail();
        addressDetail.setCreateTime(new Date());
        BeanUtils.copyProperties(req, addressDetail);
        return addressDetailService.saveOrUpdate(addressDetail);
    }

    @Override
    public PageResult<AddressDetail> addressList(AddressDetailQueryCriteria criteria, Page<Object> page) throws BizException {
        if(criteria.getUserId() == null){
            throw new BizException(USER_ID_NOT_NULL.getCode(),USER_ID_NOT_NULL.getMessage());
        }
        return addressDetailService.queryAll(criteria, page);
    }
}